<template>
  <div class="incomeRateChart flex-h-sb">
    <div class="chart">
      <div :id="id" :class="className" :style="{height:(height-40)*1.6+'px',width:width}" />
      <div :id="`${id}1`" :style="{height:(height*0.72)+'px',width:width}" />
      <div v-show="data_obj2[yName]&&data_obj2[yName].length" class="tip">
        <p>本区间最大回撤：{{sectionIncomeRate}}%</p>
        <p>({{sectionDate}})</p>
      </div>
    </div>
    <div v-if="data_obj2[yName]&&data_obj2[yName].length" class="control">
      <div v-show="showBeyondIncome" class="beyondIncome flex-h-sb flex-v-center">
        <el-input :value="yName" disabled style="width: 45%;"></el-input>
        <div class="shortline"></div>
        <el-select v-model="beyondIncome_index" @change="beyondIncomeHandle" style="width: 45%;">
          <el-option
            v-for="item in indexNames"
            :key="item.id"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </div>
      <div class="legend" :class="{'mt16': showBeyondIncome}">
        <div class="card flex-h-sb flex-v-center" v-for="(item, i) in nameLegends" :key="i">
          <div class="left flex-v-center">
            <el-checkbox style="margin: 2px 0 0 14px;" class="flex-v-center" v-model="item.status" @change="legendHandle(item.name)"></el-checkbox>
            <div class="legend-name">
              <p style="padding-left: 6px;">{{item.name}}</p>
              <div class="line" :style="`border: 1px solid ${item.color};`"></div>
            </div>
          </div>
          <div class="right">
            <p>{{legendIncome(item.name)}}（年化{{legendAnnualizedIncome(item.name)}}）</p>
            <p>最大回撤：{{legendMaxBack(item.name)}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
import { debounce, deepClone, parseTime } from '@/utils'
import { differenceInCalendarMonths } from 'date-fns' // differenceInDays
import { yAxisNumber, xReturnZero, chartDateFreq, getWeekData, getMonthData, listAfterClearNull  } from '@/utils/pro'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 200
    },
    yName: {
      type: String,
      required: true
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    data22: {
      type: Array,
      default: () => {
        return []
      }
    },
    contrastIndex_obj: {
      type: Object,
      default: () => {
        return {}
      }
    },
    legendStatus: {  // 记录图例选择状态
      type: Object,
      default: () => {
        return {}
      }
    },
    dateFreq: {  // 计算频率
      type: Number,
      default: undefined
    },
    defaultDateFreq: {  // 默认频率
      type: Number,
      default: undefined
    },
    showBeyondIncome: {  // 超额收益
      type: Boolean,
      default: false
    },
    indexNames: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      chart: null,
      chart1: null,
      listLoading: false,
      
      isIndexList: [],
      nameLegends: [],

      currentObj1: {},
      currentObj2: {},
      beyondIncome_index: '',

      xDate: [],
      data_obj1: {},
      data_obj2: {},

      day_xDate: [], // 日频y轴
      day_data_obj1: {}, // 日频收益集合
      day_data_obj2: {}, // 日频回撤集合

      week_xDate: [], // 周频y轴
      week_data_obj1: {}, // 周频收益集合
      week_data_obj2: {}, // 周频回撤集合

      month_xDate: [], // 月频y轴
      month_data_obj1: {}, // 月频收益集合
      month_data_obj2: {}, // 月频回撤集合

      color_list: ['rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)', '#cca4e3','#96ce54'], //todo 颜色 
      color_list_a: ['rgba(225,103,86,0.2)', 'rgba(129,183,236,0.2)', 'rgba(173,224,255,0.2)', 'rgba(255,155,203,0.2)'] //todo 颜色
    }
  },
  watch: {
    data: {
      handler(val) {
        if(this.showBeyondIncome&&!(this.beyondIncome_index)) this.beyondIncome_index = this.indexNames[0].name
        const list = deepClone(val)
        this.xDate = [], this.day_xDate = [], this.week_xDate = [], this.month_xDate = []
        this.data_obj1 = {}, this.day_data_obj1 = {}, this.week_data_obj1 = {}, this.month_data_obj1 = {}
        this.data_obj2 = {}, this.day_data_obj2 = {}, this.week_data_obj2 = {}, this.month_data_obj2 = {}
        this.nameLegends = []

        list[0].item.map((m, i) => {
          this.data_obj1[m.key] = []
          this.data_obj2[m.key] = []
          this.nameLegends.push({
            main: i ? 0 : 1,
            name: m.key,
            color: this.color_list[i],
            status: this.legendStatus[m.key]!=undefined ? this.legendStatus[m.key] : true
          })
        })
        this.isIndexList = list[0].item.filter(e => e.isIndex).map(e => e.key)
        const n_list = []
        const base_incomeRate_drawDown_list = []
        list.map((items, i) => {
          this.xDate.push(items.date)
          items.item.map((el, j) => {
            el.pnl = el.pnl ? Number(el.pnl) : 0
            if(n_list[j]==undefined) n_list[j] = 0
            if(el.isIndex) {
              n_list[j] = (1+n_list[j])*(1+el.pnl)-1
            }else {
              if(i>0) n_list[j] = Number(n_list[j])+el.pnl  
            }
            el.incomeRate = el.netWorth!=null ? (n_list[j]*100).toFixed(2) : null
            this.data_obj1[el.key].push(el.incomeRate)
            if(el.incomeRate == null) {
              this.data_obj2[el.key][i] = null
            }else if(Number(el.incomeRate)<Number(base_incomeRate_drawDown_list[j])) {
              if(el.isIndex) {
                this.data_obj2[el.key][i] = (((el.incomeRate-base_incomeRate_drawDown_list[j])/(Number(base_incomeRate_drawDown_list[j])+100))*100).toFixed(2)
              }else {
                this.data_obj2[el.key][i] = (el.incomeRate-base_incomeRate_drawDown_list[j]).toFixed(2)
              }
            }else {
              base_incomeRate_drawDown_list[j] = el.incomeRate
              this.data_obj2[el.key][i] = 0
            }
          })
        })

        this.currentObj1 = this.data_obj1
        this.currentObj2 = this.data_obj2

        const _defaultDateFreq = chartDateFreq(this.xDate)
        this.$emit('update:defaultDateFreq', _defaultDateFreq)
        const _dateFreq = _defaultDateFreq
        _dateFreq == 1 ? this.day_xDate=this.xDate : _dateFreq == 2 ? this.week_xDate=this.xDate : this.month_xDate=this.xDate
        _dateFreq == 1 ? this.day_data_obj1=this.data_obj1 : _dateFreq == 2 ? this.week_data_obj1=this.data_obj1 : this.month_data_obj1=this.data_obj1
        _dateFreq == 1 ? this.day_data_obj2=this.data_obj2 : _dateFreq == 2 ? this.week_data_obj2=this.data_obj2 : this.month_data_obj2=this.data_obj2

        if(this.dateFreq!=_dateFreq) {
          this.$emit('update:dateFreq', _dateFreq)
        }else {
          if(this.dateFreq==1) {
            this.dayFreqHandle()
          }else if(this.dateFreq==2) {
            this.weekFreqHandle()
          }else {
            this.monthFreqHandle()
          }
        }
      },
      deep: true,
      immediate: true
    },
    dateFreq(i) {
      if(i==1) {
        this.dayFreqHandle()
      }else if(i==2) {
        this.weekFreqHandle()
      }else if(i==3) {
        this.monthFreqHandle()
      }
    },
    showBeyondIncome(val) {
      if(val) {
        if(this.showBeyondIncome&&!(this.beyondIncome_index)) this.beyondIncome_index = this.indexNames[0].name
        this.beyondIncomeHandle(this.beyondIncome_index)
      }else {
        if(this.data_obj1['超额收益']) {
          delete this.data_obj1['超额收益']
          delete this.data_obj2['超额收益']
          this.nameLegends.shift()
          this.chart && this.chart.dispose()
          this.chart1 && this.chart1.dispose()
          this.$nextTick(() => {
            this.initChart(this.xDate, this.data_obj1, this.data_obj2)
          })
        }
      }
    },
  },
  computed: {
    sectionIncomeRate() {
      if(!(this.chart1 && this.data_obj2[this.yName])) {
        return ''
      }
      const start_i = this.chart1.getModel().option.dataZoom[0].startValue
      const end_i = this.chart1.getModel().option.dataZoom[0].endValue
      const list = this.data_obj2[this.yName].slice(start_i, end_i+1)
      const min = Math.min.apply(null, list)
      return min
    },
    sectionDate() {
      if(!(this.chart1 && this.data_obj2[this.yName])) {
        return ''
      }
      const start_i = this.chart1.getModel().option.dataZoom[0].startValue
      const end_i = this.chart1.getModel().option.dataZoom[0].endValue
      const list = this.data_obj2[this.yName].slice(start_i, end_i+1)
      const min = Math.min.apply(null, list)
      const i = list.findIndex(item => item==min)
      return this.xDate[i+start_i]
    },
    legendIncome() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj1[key])[0]
        if(!list.length) {
          return '--'
        }else {
          return list[list.length-1] + '%'
        }
      }
    },
    legendAnnualizedIncome() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj1[key])[0]
        if(!list.length) return '--'
        const start_i = this.chart ? this.chart.getModel().option.dataZoom[0].startValue : 0
        const end_i = this.chart ? this.chart.getModel().option.dataZoom[0].endValue : list.length-1
        const dm = differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) ? differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) : 1
        const yearAnnualizedincomeRate = (list.slice(-1) / (dm/12)).toFixed(2)
        return yearAnnualizedincomeRate + '%'
      }
    },
    legendMaxBack() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj2[key])[0]
        if(!list.length) return '--'
        const min = Math.min.apply(null, list)
        return Math.abs(min) + '%'
      }
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    this.chart1.dispose()
    this.chart1 = null
  },
  methods: {
    initChart(xDate, obj1, obj2) {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart1 = echarts.init(document.getElementById(this.id+'1'))

      let all_list_obj1 = []
      const series1 = []
      const series2 = []

      const start_i = this.chart.getModel() ? this.chart.getModel().option.dataZoom[0].startValue : 0
      const end_i = this.chart.getModel() ? this.chart.getModel().option.dataZoom[0].endValue : obj1[this.yName].length
      const view_obj = [{}, {}]

      if(Object.keys(obj1).length) {
        Object.keys(obj1).forEach(key => {
          view_obj[0][key] = obj1[key].slice(start_i, end_i)
          const item = obj1[key]
          if(this.legendStatus[key]==undefined||this.legendStatus[key]) all_list_obj1 = [...all_list_obj1, ...item]
          series1.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: this.nameLegends.find(item => item.name==key).color
            },
            data: item,
            connectNulls: true
          })
        })
      }
      const yVal = yAxisNumber(all_list_obj1)

      if(Object.keys(obj2).length) {
        Object.keys(obj2).forEach((key, i) => {
          const nameLegend = this.nameLegends.find(item => item.name==key)
          view_obj[1][key] = obj2[key].slice(start_i, end_i)
          const item = obj2[key]
          series2.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            itemStyle: {
              color: nameLegend.color
            },
            lineStyle: {
              width: 1.6
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: nameLegend.main ? this.color_list_a[0] : 'rgba(0,0,0,0)'
              }, {
                offset: 1,
                color: nameLegend.main ? this.color_list[0] : 'rgba(0,0,0,0)'
              }])
            },
            data: item,
            connectNulls: true
          })
          if(nameLegend.main) {
            series2[i].markLine = {
              data: [
                { 
                  type: 'min'
                }
              ],
              label: { show: false }
            }
          }
        })
      }
      view_obj[2] = this.xDate.slice(start_i, end_i)
      this.$emit('viewObj', view_obj)

      this.chart.setOption({
        title: {
          left: 52,
          text: '收益',
          top: 10,
          textStyle: {
            color: '#595959',
            fontWeight: 400
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter: (params) => {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${parseTime(params[0].name)}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span>
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: 10,
          left: 55,
          right: 10,
          bottom: '6%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          show: false,
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '10%',
          textStyle: {
            color: '#90979c',
            fontSize: 11
          },
          formatter: (name) => {
            const start_i = this.chart.getModel().option.dataZoom[0].startValue
            const end_i = this.chart.getModel().option.dataZoom[0].endValue
            const obj = this.chart.getOption().series.find(item => item.name==name)
            const dm = differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) ? differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) : 1
            const yearAnnualizedincomeRate = (obj.data[end_i] / (dm/12)).toFixed(2)
            return obj.data[end_i] ? name +'   '+ obj.data[end_i] + '%' + ' (年化:' + yearAnnualizedincomeRate + '%)' : name +'   '+ '--'
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [{
          show: false,
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto',
            margin: 20,
          },
          data: xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: yVal[0],
            max: yVal[1],
            interval: yVal[2],
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                // return value.toFixed(0) + '%' // todo y轴颗粒度
                return value.toFixed(2) + '%'
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100,
          zoomLock: true
        }, {
          show: false,
          start: 0,
          end: 100,
          realtime: true,
          height: '6%',
          bottom: '8%',
        }],
        series: series1
      })

      this.chart1.setOption({
        title: {
          left: 52,
          text: '回撤',
          top: 10,
          textStyle: {
            color: '#595959',
            fontWeight: 400
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${parseTime(params[0].name)}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: 10,
          left: 55,
          right: 10,
          bottom: '37%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          show: false,
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '2%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
            // rich:{
            //   a:{
            //     color: '#C00',
            //     align: 'center',
            //     padding: [0, 0, 0, 5]
            //   },
            //   b:{
            //     color: '#088',
            //     align: 'center',
            //     padding: [0, 0, 0, 5]
            //   }
            // }
          },
          formatter: (name) => {
            const start_i = this.chart1.getModel().option.dataZoom[0].startValue
            const end_i = this.chart1.getModel().option.dataZoom[0].endValue
            const list = this.data_obj2[name].slice(start_i, end_i+1)
            const min = Math.min.apply(null, list)
            // return min<-20 ? name + '{a|' + min + '%}' : name + '{b|' + min + '%}'  // 此处通过条件判断赋值abc,可实现动态样式
            return name +'   '+ min + '%'
          },
          selected: this.legendStatus
        },
  
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          axisLine: {
            show: false,
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false,
            alignWithLabel: true
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            margin: 20,
            interval: 'auto'
          },
          data: xDate
        }],
        yAxis: [
          {
            type: 'value',
            splitNumber: 4,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value + '%'
              }
            }
          }
        ],
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100,
          zoomLock: true
        }, {
          brushSelect: false,
          realtime: true, // 实时更新系列的视图
          height: '14%',
          bottom: '1%',
        }],
        series: series2
      })

      this.chart.on('highlight', (params) => {
        const obj = params.batch[0]
        this.chart1.dispatchAction({
          type: 'showTip',
          seriesIndex: obj.seriesIndex,
          dataIndex: obj.dataIndex
        })
      })
      this.chart1.on('highlight', (params) => {
        const obj = params.batch[0]
        this.chart.dispatchAction({
          type: 'showTip',
          seriesIndex: obj.seriesIndex,
          dataIndex: obj.dataIndex
        })
      })

      this.chart.on('datazoom', debounce(() => {
        const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
        const end_i = this.chart.getModel().option.dataZoom[0].endValue
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        const op_res = xReturnZero(this.data_obj1, this.data_obj2, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1
        const view_obj = [{}, {}]
        this.currentObj1 = {}
        this.currentObj2 = {}
        Object.keys(this.data_obj1).forEach(key => {
          const _obj1 = op.series.filter(item => item.name==key)[0]
          const _obj2 = op1.series.filter(item => item.name==key)[0]
          view_obj[0][key] = _obj1.data.slice(baseline_i, end_i+1)
          view_obj[1][key] = _obj2.data.slice(baseline_i, end_i+1)

          this.currentObj1[key] = view_obj[0][key]
          this.currentObj2[key] = view_obj[1][key]
        })
        view_obj[2] = this.xDate.slice(baseline_i, end_i+1)
        this.$emit('viewObj', view_obj)
        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        op1.dataZoom[0].start = op.dataZoom[0].start
        op1.dataZoom[0].end = op.dataZoom[0].end
        op1.dataZoom[1].start = op.dataZoom[1].start
        op1.dataZoom[1].end = op.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      }, 500))
      
      this.chart1.on('datazoom', debounce(() => {
        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        const op_res = xReturnZero(this.data_obj1, this.data_obj2, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1
        const view_obj = [{}, {}]
        this.currentObj1 = {}
        this.currentObj2 = {}
        Object.keys(this.data_obj1).forEach(key => {
          const _obj1 = op.series.filter(item => item.name==key)[0]
          const _obj2 = op1.series.filter(item => item.name==key)[0]
          view_obj[0][key] = _obj1.data.slice(baseline_i, end_i+1)
          view_obj[1][key] = _obj2.data.slice(baseline_i, end_i+1)

          this.currentObj1[key] = view_obj[0][key]
          this.currentObj2[key] = view_obj[1][key]
        })
        view_obj[2] = this.xDate.slice(baseline_i, end_i+1)
        this.$emit('viewObj', view_obj)
        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        op.dataZoom[0].start = op1.dataZoom[0].start
        op.dataZoom[0].end = op1.dataZoom[0].end
        op.dataZoom[1].start = op1.dataZoom[1].start
        op.dataZoom[1].end = op1.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      }, 500))

      this.chart.on('legendselectchanged', (obj) => {
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        op1.legend[0].selected = obj.selected

        // 记录图例状态
        this.savaLegendStatus(obj.selected)

        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue
        const op_res = xReturnZero(this.data_obj1, this.data_obj2, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1
        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      })

      this.chart1.on('legendselectchanged', (obj) => {
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        op.legend[0].selected = obj.selected

        // 记录图例状态
        this.savaLegendStatus(obj.selected)

        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue
        const op_res = xReturnZero(this.data_obj1, this.data_obj2, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1
        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      })
    
      this.chart.on('globalout', () => {
        this.chart1.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: -1
        })
      })
      this.chart1.on('globalout', () => {
        this.chart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: -1
         })
      })
    },

    legendHandle(name) {
      this.chart.dispatchAction({
        type: 'legendToggleSelect',
        name
      })
    },

    beyondIncomeHandle(val) {
      if(!val) return
      const name1 = this.yName
      const name2 = val
      if(this.nameLegends[0].name!='超额收益') {
        this.nameLegends.unshift({
          name: '超额收益',
          color: '#F6BD16',
          status: true
        })
      }
      this.data_obj1['超额收益'] = []
      this.data_obj2['超额收益'] = []
      let base_val = 0
      this.data_obj1[name1].forEach((e, i) => {
        if(e!=null && this.data_obj1[name2][i]!=null) {
          const num = (e - this.data_obj1[name2][i]).toFixed(2)
          this.data_obj1['超额收益'].push(num)
          if(Number(num)>base_val) {
            base_val = Number(num)
            this.data_obj2['超额收益'].push(0)
          }else {
            this.data_obj2['超额收益'].push((num - base_val).toFixed(2))
          }
        }else {
          this.data_obj1['超额收益'].push(null)
          this.data_obj2['超额收益'].push(null)
        }
      })
      this.chart && this.chart.dispose()
      this.chart1 && this.chart1.dispose()
      this.$nextTick(() => {
        this.initChart(this.xDate, this.data_obj1, this.data_obj2)
      })
    },

    dayFreqHandle() {
      this.xDate = this.day_xDate
      this.data_obj1 = this.day_data_obj1
      this.data_obj2 = this.day_data_obj2
      // 如果超额曲线显示且对应指数也存在, 则保留超额曲线
      if(this.showBeyondIncome&&this.indexNames.findIndex(e => e.name==this.beyondIncome_index)!=-1) {
        this.beyondIncomeHandle(this.beyondIncome_index)
      }else {
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        this.$nextTick(() => {
          this.initChart(this.xDate, this.data_obj1, this.data_obj2)
        })
      }
    },
    weekFreqHandle() {
      let res = []
      if(this.week_xDate.length) {
        this.xDate = this.week_xDate
        this.data_obj1 = this.week_data_obj1
        this.data_obj2 = this.week_data_obj2
      }else if(this.day_xDate.length) {
        res = getWeekData(this.day_xDate, this.day_data_obj1, this.day_data_obj2)
        this.xDate = res[0]
        this.week_xDate = res[0]
        this.data_obj1 = res[1]
        this.week_data_obj1 = res[1]
        this.data_obj2 = res[2]
        this.week_data_obj2 = res[2]
      }else {
        this.week_xDate = this.xDate
        this.week_data_obj1 = this.data_obj1
        this.week_data_obj2 = this.data_obj2
      }
      if(this.showBeyondIncome&&this.indexNames.findIndex(e => e.name==this.beyondIncome_index)!=-1) {
        this.beyondIncomeHandle(this.beyondIncome_index)
      }else {
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        this.$nextTick(() => {
          this.initChart(this.xDate, this.data_obj1, this.data_obj2)
        })
      }
    },
    monthFreqHandle() {
      let res = []
      if(this.week_xDate.length) {
        res = getMonthData(this.week_xDate, this.week_data_obj1, this.week_data_obj2)
        this.xDate = res[0]
        this.month_xDate = res[0]
        this.data_obj1 = res[1]
        this.month_data_obj1 = res[1]
        this.data_obj2 = res[2]
        this.month_data_obj2 = res[2]
      }else if(this.day_xDate.length) {
        res = getMonthData(this.day_xDate, this.day_data_obj1, this.day_data_obj2)
        this.xDate = res[0]
        this.month_xDate = res[0]
        this.data_obj1 = res[1]
        this.month_data_obj1 = res[1]
        this.data_obj2 = res[2]
        this.month_data_obj2 = res[2]
      }else {
        this.month_xDate = this.xDate
        this.month_data_obj1 = this.data_obj1
        this.month_data_obj2 = this.data_obj2 
      }
      if(this.showBeyondIncome&&this.indexNames.findIndex(e => e.name==this.beyondIncome_index)!=-1) {
        this.beyondIncomeHandle(this.beyondIncome_index)
      }else {
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        this.$nextTick(() => {
          this.initChart(this.xDate, this.data_obj1, this.data_obj2)
        })
      }
    },

    // 记录图例状态
    savaLegendStatus(obj) {
      const res = JSON.parse(JSON.stringify(this.legendStatus))
      Object.keys(obj).map(key => {
        const status = obj[key]
        res[key] = status
      })
      this.$emit('legendStatus', res)
    },

  }
}
</script>

<style lang="scss" scoped>
.incomeRateChart {
  .chart {
    width: calc( 100% - 432px );
    position: relative;
    .tip {
      position: absolute;
      bottom: 76px;
      left: calc( 100% - 180px );
      color: #666;
      p { text-align: right; }
    }
  }
  .control {
    display: flex;
    flex-direction: column;
    margin-left: 24px;
    .beyondIncome {
      .shortline {
        width: 20px;
        border: 1px solid #D9D9D9;
      }
    }
    .legend {
      min-width: 432px;
      height: 100%;
      overflow: auto;
      background: #FAFAFA;
      border-radius: 8px;
      .card {
        height: 48px;
        cursor: pointer;
        padding: 0 13px 0 14px;
        box-shadow: inset 0px -1px 0px 0px #F0F0F0;
        &:hover {
          background: #FFFFFF;
          box-shadow: inset 0px -1px 0px 0px #F0F0F0;
        }
        .legend-name {
          .line {
            width: 28px;
            margin-left: 6px;
          }
        }
        .right {
          font-size: 12px;
          color: #8C8C8C;
          p {text-align: right;}
        }
      }
    }
    .mt16 {
      margin-top: 16px;
    }
  }
}
</style>

